package toubiao.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import dao.ConditionFilterFactory;
import dao.domain.ConditionFilterClass;
import toubiao.domain.vo.assist.PageHelper;
import toubiao.domain.vo.easyUi.DataGrid;
import toubiao.exception.CustomException;
import toubiao.service.impl.DataGridServiceImpl;
import toubiao.service.impl.ProjectServiceImpl;
import toubiao.utils.ProUtilFileSuffix;
import toubiao.utils.ProUtilLogger;
import toubiao.utils.filter.FilterCondition;
import toubiao.utils.filter.FilterHqlFactory;
import toubiao.utils.filter.OrderCondition;
import toubiao.utils.filter.OrderHqlFactory;
import utils.UtilController;
import utils.UtilDate;
import utils.UtilJackson;
import utils.easyui.domain.EzDatagrid;
import static toubiao.utils.ProUtilLogger.rootLogger;



@Controller
@RequestMapping("/common/dataGrid")
public class DataGridController {
	private Logger logger=ProUtilLogger.getRootLogger();
	
	@Autowired
	private ProjectServiceImpl projectService;
	
	@Autowired
	private DataGridServiceImpl dataGridService;

	@RequestMapping("/{objectName}/dataGrid.jspPage")
	public ModelAndView JspPageGetProjectGrid(@PathVariable("objectName") String objectName){
		//rootLogger.info("in DataGridController");
		//System.out.println("in DataGridController");
		ModelAndView modelAndView=new ModelAndView();
		modelAndView.setViewName("/module/common/dataGrid/dataGrid");
		modelAndView.addObject("objectName", objectName);
		return modelAndView;
	}
	
	/**@description 使用的比较新的utility包中的 筛选条件 生成方式,ConditionFilterFactory
	 * @param request
	 * @param ph
	 * @param className 标识 是那个对象,关系到service层查找 hqlbase 和 dao的调用
	 * @return
	 * @throws CustomException 
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 */
	@RequestMapping("/ldrdSelect/{objectName}/griddata.json")
	@ResponseBody
	public EzDatagrid jsonDataGridForLdtdSelectByConditionFilter(HttpServletRequest request,PageHelper ph,@PathVariable("objectName") String className) throws InstantiationException, IllegalAccessException, CustomException{
		ConditionFilterClass filterClass=ConditionFilterFactory.getConditionFilterClassFromHttpRequest(request);
		logger.info(filterClass+"");
		logger.info(UtilJackson.getJson(filterClass));
		logger.info(className);
		EzDatagrid datagrid=dataGridService.getDataGridForLdtdSelectByConditionFilter(filterClass,ph,className);
		return datagrid;
	}
	
	
	/**
	 * 通过分页形式，获取项目信息，其中包换过滤信息和排序信息:conditionsJson;orderConditionJson
	 * 
	 * @param project
	 * @param PageHelper
	 * @return
	 * @throws CustomException 
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping("/{objectName}/griddata.json")
	@ResponseBody
	public DataGrid jsonDataGridByHqlCondition(@PathVariable("objectName") String objectName, PageHelper ph,HttpServletRequest request) throws CustomException  {
		String filterConditionsJson=request.getParameter("conditionsJson");
		String orderConditionsJson=request.getParameter("orderConditionJson");
		List<FilterCondition> filterConditionList=FilterHqlFactory.json2FilterConditionList(filterConditionsJson);
		List<OrderCondition> orderConditionList=OrderHqlFactory.json2OrderConditionList(orderConditionsJson);
		
		//logger.info(conditionList.size()+"");
		for(FilterCondition filterCondition:filterConditionList){
			ProUtilLogger.rootLogger.info(filterCondition.toString());
			
		}
		
		DataGrid dataGrid=null;
		objectName=objectName.trim();
		if(objectName.equalsIgnoreCase("project") || objectName.equalsIgnoreCase("contract") ){
			try {
				dataGrid=dataGridService.getDataGridByConditions(objectName,filterConditionList, orderConditionList, ph);
			} catch (ClassNotFoundException | InstantiationException
					| IllegalAccessException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				throw new RuntimeException("网页错误，请与管理员联系");
			}
		}
		
		if(dataGrid==null){
			dataGrid=new DataGrid();
			dataGrid.setTotal(0L);
			dataGrid.setRows(new ArrayList<>());
		}
		return dataGrid;
	}
	
	@RequestMapping("/{objectName}/downloadAll")
	public void fileDownloadAll(@PathVariable("objectName") String objectName,HttpServletRequest request, HttpServletResponse response) throws CustomException, IOException{
		String fileType=request.getParameter("fileType");
		String fileAbsPath;
		try {
			fileAbsPath = dataGridService.downloadFileAll(objectName,fileType);
		} catch (ClassNotFoundException | InstantiationException
				| IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new CustomException("下载失败，请与管理员联系.");
		}
		String suffix=ProUtilFileSuffix.getFileSuffix(fileType);
        String dateString=UtilDate.getFormateDate(new Date(), "yyMMdd");
        String savedName="所有项目_"+dateString+suffix;
        UtilController.downloadFile(fileAbsPath, savedName, request, response);
	}

	//下载Excel checked
	@RequestMapping("/{objectName}/downloadChecked")
	public void fileDownloadChecked(@PathVariable("objectName") String objectName,HttpServletRequest request, HttpServletResponse response,String ids) throws CustomException {
		if(ids==null || ids.trim().equals("")){
			throw new CustomException("ids 为空.");
		}
		String fileType=request.getParameter("fileType");
		String suffix=ProUtilFileSuffix.getFileSuffix(fileType);
        try {
        	String fileAbsPath=dataGridService.downloadFileByIds(objectName,fileType, ids);
            String dateString=UtilDate.getFormateDate(new Date(), "yyMMdd");
            String savedName="勾选项目_"+dateString+suffix;
			UtilController.downloadFile(fileAbsPath, savedName, request, response);
		} catch (IOException | ClassNotFoundException | InstantiationException | IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new CustomException("下载失败，请与管理员联系.");
		}
	}
	
	//下载Excel filtered
	@RequestMapping("/{objectName}/downloadFiltered")
	public void fileDownloadFiltered(@PathVariable("objectName") String objectName,HttpServletRequest request, HttpServletResponse response) throws CustomException{
		String filterConditionsJson=request.getParameter("conditionsJson");
		String orderConditionsJson=request.getParameter("orderConditionJson");
		String fileType=request.getParameter("fileType");
		String suffix=ProUtilFileSuffix.getFileSuffix(fileType);
		List<FilterCondition> filterConditionList=FilterHqlFactory.json2FilterConditionList(filterConditionsJson);
		List<OrderCondition> orderConditionList=OrderHqlFactory.json2OrderConditionList(orderConditionsJson);
		
        try {
        	String fileAbsPath=dataGridService.downloadFileByCondition(objectName,fileType, filterConditionList, orderConditionList);
    		String dateString=UtilDate.getFormateDate(new Date(), "yyMMdd");
            String savedName="筛选项目_"+dateString+suffix;
			UtilController.downloadFile(fileAbsPath, savedName, request, response);
		} catch (IOException | InstantiationException | IllegalAccessException | ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new CustomException("下载失败，请与管理员联系.");
		}
	}
}
